##########################################################################################

library(data.table)
library(optparse)
library(parallel)

##########################################################################################

option_list <- list(
    make_option(c("--sample_list_file"), type = "character"),
    make_option(c("--sample_list_public_file"), type = "character"),
    make_option(c("--tmm_file"), type = "character"),
    make_option(c("--tmm_combine_file"), type = "character"),
    make_option(c("--tmm_combinepublic_file"), type = "character"),
    make_option(c("--out_path"), type = "character")
)

if(1!=1){
    
    sample_list_file <- "~/20220915_gastric_multiple/dna_combinePublic/config/tumor_normal.class.list"
    sample_list_public_file <- "~/20220915_gastric_multiple/dna_combinePublic/public_ref/combine/MutationInfo.combine.tsv"
    tmm_file <- "~/20220915_gastric_multiple/dna_combinePublic/mRNA/CombineCounts.FilterLowExpression.TMM.tsv"
    tmm_combine_file <- "~/20220915_gastric_multiple/dna_combinePublic/mRNA/CombineCounts.FilterLowExpression-MergeMutiSample.TMM.tsv"
    tmm_combinepublic_file <- "~/20220915_gastric_multiple/dna_combinePublic/mRNA/CombineCounts.TCGA_NJMU.FilterLowExpression.TMM.tsv"
    out_path <- "~/20220915_gastric_multiple/dna_combinePublic/mRNA"

}

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

sample_list_file <- opt$sample_list_file
sample_list_public_file <- opt$sample_list_public_file
tmm_file <- opt$tmm_file
tmm_combine_file <- opt$tmm_combine_file
tmm_combinepublic_file <- opt$tmm_combinepublic_file
out_path <- opt$out_path

##########################################################################################

info <- data.frame(fread(sample_list_file))
info_public <- data.frame(fread(sample_list_public_file))
info_public <- subset( info_public , MS_Type=="MSS" )
info_public$ID <- paste0( info_public$Tumor , "_" , info_public$Class )

dat_tpm <- data.frame(fread(tmm_file))
colnames(dat_tpm) <- gsub("[.]" , "-" , colnames(dat_tpm))
dat_tpm_combine <- data.frame(fread(tmm_combine_file))
dat_tpm_public_combine <- data.frame(fread(tmm_combinepublic_file))
colnames(dat_tpm_public_combine) <- gsub("[.]" , "-" , colnames(dat_tpm_public_combine))

## 去除TCGA的Normal
dat_tpm_public_combine <- dat_tpm_public_combine[ , grep( "Normal" , colnames(dat_tpm_public_combine) , invert = T )]

##########################################################################################
sid <- paste0(info$ID , "_" , info$Class_sub )
#sid_normal <- paste0(info$ID , "_Normal" )
result <- dat_tpm[,colnames(dat_tpm) %in% c("gene_id" , sid)]
out_file <- paste0( out_path , "/" , "CombineTMM.DNAUse.tsv" )
write.table( result , out_file , row.names = F , sep = "\t" , quote = F )

sid <- unique(paste0(info$ID , "_" , info$Class ))
#sid_normal <- paste0(info$ID , "_Normal" )
result_combine <- dat_tpm_combine[,colnames(dat_tpm_combine) %in% c("gene_id" , sid)]
out_file <- paste0( out_path , "/" , "CombineTMM.DNAUse.MergeMutiSample.tsv" )
write.table( result_combine , out_file , row.names = F , sep = "\t" , quote = F )

##########################################################################################
## 去除TCGA和NJMU批次效应以后的结果
sid <- paste0(info$ID , "_" , info$Class_sub )
#sid_normal <- paste0(info$ID , "_Normal" )
tcga_sample <- colnames(dat_tpm_public_combine)[colnames(dat_tpm_public_combine) %in% info_public$ID]

result_combine_public <- dat_tpm_public_combine[,colnames(dat_tpm_public_combine) %in% c("gene_id" , sid , tcga_sample)]
out_file <- paste0( out_path , "/" , "CombineTMM.DNAUse.NJMU_TCGA.tsv" )
write.table( result_combine_public , out_file , row.names = F , sep = "\t" , quote = F )

##########################################################################################
## 同一人多个同类型样本，表达合并
dat_tpm_all <- data.frame()

for( id in unique(info$ID) ){

    print(id)
    tmp_info <- subset( info , ID == id )

    ## 若样本存在RNA数据
    if(length(grep( id , colnames(result_combine_public))) > 0 ){
        result <- data.frame()
        ## 若一个人同一病理类型多个样本，均中位数
        for(class in unique(tmp_info$Class)){
            tmp_sample <- paste0( id , "_" , tmp_info[tmp_info$Class==class,"Class_sub"] )
            tmp_tpm <- result_combine_public[,c("gene_id" , tmp_sample)]

            if(ncol(tmp_tpm) > 2){
                value <- apply( tmp_tpm[,-1] , 1 , median )
            }else{
                value <- tmp_tpm[,-1]
            }
            
            result_tmp <- data.frame( gene_id = tmp_tpm$gene_id , sample = value )
            colnames(result_tmp)[2] <- paste0( id , "_" , class)

            if( nrow(result) > 0){
                result <- merge(result , result_tmp)
            }else{
                result <- result_tmp
            }
        }

        ## Normal样本
        tmp_sample <- paste0( id , "_Normal"  )
        if( length(grep( tmp_sample , colnames(result_combine_public))) > 0 ){
            tmp_tpm <- result_combine_public[,c("gene_id" , tmp_sample)]
            value <- tmp_tpm[,-1]
            result_tmp <- data.frame( gene_id = tmp_tpm$gene_id , sample = value )
            colnames(result_tmp)[2] <- paste0( id , "_" , "Normal")

            ## 输出结果
            result <- merge(result , result_tmp)
        }
        
        if(nrow(dat_tpm_all) > 0 ){
            dat_tpm_all <- merge( dat_tpm_all , result , by = "gene_id" )
        }else{
            dat_tpm_all <- result
        }   
    }
}


tcga_sample <- colnames(dat_tpm_public_combine)[colnames(dat_tpm_public_combine) %in% info_public$ID]
tmm_tcga <- dat_tpm_public_combine[,colnames(dat_tpm_public_combine) %in% c("gene_id" , tcga_sample)]

result_combine_public_merge <- merge( dat_tpm_all , tmm_tcga , by = "gene_id" )
out_file <- paste0( out_path , "/" , "CombineTMM.DNAUse.NJMU_TCGA.MergeMutiSample.tsv" )
write.table( result_combine_public_merge , out_file , row.names = F , sep = "\t" , quote = F )
